<template>
  <div class="charts-search-block business-select-box">
    <div class="charts-search-block-content">
      <div class="charts-search-select">
        <span>{{$t('common.base.workTime')}}：</span>
        <el-select :clearable="false" v-model="formData.dataType" :placeholder="$t('common.base.pleaseSelect')" class="business-dateType-picker">
          <el-option v-for="item in dataTypeList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker v-if="dataPickerType === 'monthrange'" class="business-date-picker business-select-mr"
          v-model="formData.monthTime" type="monthrange" :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp" :default-time="['00:00:00', '23:59:59']"
          align="right" :clearable="false">
        </el-date-picker>
        <el-date-picker v-if="dataPickerType === 'daterange'" class="business-date-picker" v-model="formData.dateTime"
          type="daterange" :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp" :default-time="['00:00:00', '23:59:59']" :clearable="false" align="right">
        </el-date-picker>
      </div>
      <div class="charts-search-select">
        <span>OEM：</span>
        <el-select :placeholder="$t('common.base.pleaseSelect')" multiple v-model="formData.oems" @change="chooseOEM" style="width:180px"
          :clearable="true" collapse-tags>
          <el-option v-for="item in oemList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.systemKeyword.customer')}}：</span>
        <biz-search-customer-select style="width:180px" :multiple="true" :value="formData.customerIds"
          @input="chooseCustomer" :remote-method="fetchCustomer" value-key="id" :collapsed="true" :placeholder="$t('report.common.allCustomer')" />
      </div>
      <div class="charts-search-select usual-biz-team-select">
        <span>{{$t('common.base.department')}}：</span>
        <!-- <el-select v-model="formData.tagIds" @change="chooseTags" multiple :placeholder="$t('common.base.pleaseSelect')" collapse-tags filterable
          style="width:180px;">
          <el-option v-for="item in tagList" :key="item.id" :label="item.tagName" :value="item.id">
          </el-option>
        </el-select> -->
        <biz-team-select
          :value="formData.tagIds"
          collapse
          multiple
          style="width:180px;"
          @input="chooseTags"
          :fetch-func="getTagList"
        />
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.person')}}：</span>
        <el-select v-model="formData.userIds" multiple :placeholder="$t('common.base.pleaseSelect')" collapse-tags filterable style="width:180px">
          <el-option v-for="item in userList" :key="item.userId" :label="item.displayName" :value="item.userId">
          </el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.form.preview.serviceItem.label3')}}</span>
        <el-select :placeholder="$t('common.base.all')"  v-model="formData.serviceTypes" multiple filterable collapse-tags :clearable="true"
          style="width:180px">
          <el-option v-for="item in serviceTypesList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('report.mtbtSelect.eographicalLocation')}}：</span>
        <el-select :placeholder="$t('common.base.all')"  v-model="formData.positions" multiple filterable collapse-tags :clearable="true"
          style="width:180px">
          <el-option v-for="item in positionsList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
    </div>
    <div class="charts-search-block-operator">
      <el-button type='primary' @click="handlerSearchClick">
        {{ $t('common.base.search') }}
      </el-button>
    </div>
  </div>
</template>
<script>

import { lastDayOfMonth, firstDayOfMonth, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { t } from '@src/locales';

// api
import {
  workHoursReportData,
  workHoursReportExport,
  getCustomerOEMDatabase,
  getOldCustomerList,
  getWorkHoursTagUserList,
  getAllSelectDataList
} from '@src/api/ssbReports'

import { getTagList } from '@src/api/SettingApi.ts';

export default {
  name: 'work-hours-select',
  data () {
    return {
      formData: {
        dateTime: [], // 日时间
        monthTime: [], // 月时间
        oems: [],
        customerIds: [], // 客户Ids
        dataType: 'month', // 日月维度
        tagIds: [],
        userIds: [],
        serviceTypes: [],
        positions: []
      },
      dataTypeList: [
        {
          label:t('common.base.month'),
          value:'month'
        },
        {
          label:t('common.base.day2'),
          value:'day'
        },
      ],
      oemList: [], // OEM列表
      tagList: [],
      userList: [],
      serviceTypesList: [],
      positionsList: [],
      OEMFieldName: '',
    }
  },
  computed: {
    dataPickerType () {
      return this.formData.dataType === 'month' ? 'monthrange' : 'daterange'
    }
  },
  created () {
    this.formData.dateTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.formData.monthTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.getRequestParam()
  },
  methods: {
    getOemList () {
      return getCustomerOEMDatabase().then(res => {
        if (res.code == 0) {
          this.oemList = res.data.database
          // this.formData.oems = res.data.database[0] || ''
          this.OEMFieldName = res.data.fieldName
        }
      })
    },
    async getTagList (params) {
      try {
        return await getTagList(params);
      } catch (error) {
        console.error("get tag list error", error);
      }
    },
    getUserList () {
      const { tagIds } = this.formData
      let ids = [];
      tagIds.forEach(item=>{
        ids.push(item.id)
      })
      return getWorkHoursTagUserList([...ids]).then(res => {
        if (res.code == 0) {
          this.userList = res.data || [];
        }
      })
    },
    chooseTags (value) {
      this.formData.tagIds = value;
      this.formData.userIds = []
      this.userList = []
      if (this.formData.tagIds.length == 0) return;
      this.getUserList()
    },
    chooseOEM () {
      this.formData.customerIds = []
    },
    fetchCustomer (params) {
      if (this.formData.oems?.length) {
        params['conditions'] = [{ property: this.OEMFieldName, inValue: this.formData.oems, key: null, operator: 'in' }]
      } else {
        params['conditions'] = []
      }
      return getOldCustomerList({ ...params })
    },
    chooseCustomer (value) {
      this.formData.customerIds = value
    },
    handlerSearchClick () {
      this.getData()
    },
    /**
     * @des 初始化搜索所需数据
     */
    getRequestParam () {
      // 影响报表内容的需要放在arr
      let arr = [];
      arr.push(this.getOemList());
      Promise.all(arr).then(() => {
        this.getData()
      })
      getAllSelectDataList().then(res => {
        if (res.code == 0) {
          const { serviceTypes, positions } = res.data;
          this.serviceTypesList = serviceTypes;
          this.positionsList = positions;
        }
      })
    },
    getSearchParams () {
      const { dataType, monthTime, dateTime, oems, customerIds, positions, serviceTypes, userIds, tagIds } = this.formData;
      let tagIds_ = [];
      tagIds.forEach(item=>{
        tagIds_.push(item.id)
      })
      let params = {
        createDateStart: dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd: dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : +dayTimeEnd(this.formData.dateTime[1]),
        oems: oems ? oems : [],
        customerIds: customerIds.map(item => {
          return item.id
        }),
        timeDimension: dataType,
        tagIds:tagIds_,
        userIds,
        positions,
        serviceTypes,
        isExport: false
      }
      return params
    },
    getData () {
      const params = this.getSearchParams();
      this.$emit('change-loading', { type: 1, state: true })
      workHoursReportData(params).then(res => {
        if (res.code == 0) {
          this.$emit('updateData', { data: res.data, haveUsers: this.formData.customerIds.length > 0 })
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.$emit('change-loading', { type: 1, state: false })
      })
    },
    export () {
      this.$emit('change-loading', { type: 2, state: true })
      const params = this.getSearchParams();
      params.isExport = true;
      workHoursReportExport(params, true, { responseType: 'blob' }).then(blob => {
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.$t('report.workHoursChart.reportName');
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() => {
        this.$emit('change-loading', { type: 2, state: false })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../business.scss';
</style>
<style lang="scss">
.usual-biz-team-select{
  .el-input--small .el-input__inner{
    height: auto !important;
  }
  .biz-team-select-clear{
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>